package com.oa.system.controller;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.*;
import com.joneying.common.web.response.Resp;
import com.oa.core.config.AliOssConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Description;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/file")
@Api(description = "文件接口")
public class FileController {

    @Autowired
    private AliOssConfig ossConfig;

    public OSSClient ossClient() {
        return new OSSClient(ossConfig.getOssEndpoint(), ossConfig.getOssAccessKeyId(), ossConfig.getOssAccessKeySecret());
    }


    public String getFileAddress(){
        return "https://" + ossConfig.getBucketName() + "." + ossConfig.getOssEndpoint();
    }

    @RequestMapping("/upload")
    @Description("上传")
    @ApiOperation(value = "上传")
    public Object upload(@RequestPart("upfile") MultipartFile file) {
        OSSClient ossClient = ossClient();

        String fileName = UUID.randomUUID().toString().replace("-", "")+ "." + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);

        try {
            ossClient.putObject(ossConfig.getBucketName(), fileName, file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            ossClient.shutdown();
        }

        Map res = new HashMap();
        res.put("oldName", file.getOriginalFilename());
        res.put("newName", fileName);
        res.put("uri", getFileAddress() + "/" + fileName);
        return new Resp().success(res);
    }

    @RequestMapping("/download")
    @Description("下载")
    @ApiOperation(value = "下载")
    public void download(HttpServletRequest request, HttpServletResponse response) {

        String fileName = request.getParameter("fileName");

        // 配置文件下载
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");

        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        try {
            // 下载文件能正常显示中文
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

            URL url = new URL(getFileAddress() + "/" + fileName);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            bis = new BufferedInputStream(connection.getErrorStream());
            bos = new BufferedOutputStream(new FileOutputStream(fileName));

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = bis.read(bytes)) != -1) {
                bos.write(bytes, 0, len);
            }
            connection.disconnect();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bis.close();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    //获取存储对象的名字
    @RequestMapping("/list")
    public Object listObject() {
        OSSClient ossClient = ossClient();
        // 获取指定bucket下的所有Object信息
        ObjectListing listing = ossClient.listObjects(ossConfig.getBucketName());

        ossClient.shutdown();
        return listing.getObjectSummaries();
    }
}
